/*
 * @Author: zxc
 * @Date: 2020-11-14 14:22:04
 * @LastEditTime: 2020-11-16 13:35:32
 * @LastEditors: zxc
 * @Description:三数之和为0
 */
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  if (nums == null || nums.length < 3) return []
  let res = []
  const len = nums.length
  nums.sort((a, b) => a - b)
  for (let i = 0; i < len; i++) {
    if (nums[i] > 0) break
    if (i > 0 && nums[i] == nums[i - 1]) continue
    let L = i + 1
    let R = len - 1
    while (L < R) {
      const sum = nums[i] + nums[L] + nums[R]
      if (sum == 0) {
        res.push([nums[i], nums[L], nums[R]])
        while (L < R && nums[L] == nums[L + 1]) L++
        while (L < R && nums[R] == nums[R - 1]) R--
        L++
        R--
      } else if (sum < 0) L++
      else if (sum > 0) R--
    }
  }
  return res
}
